﻿using System;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using IntraVision.Web;
using IntraVision.Web.Security;
using IntraVision.Web.Filter;
using Model;
using System.Text;
using LZMA;

[AllowedRole("IsAdmin")]
public class NotarialActionController : TableController<NotarialServiceDataContext, NotarialAction>
{
    protected bool _TaskActionOnly = false;

    public void Select()
    {
        ViewData["hidecb"] = ViewData["popup"] = true;

        _TaskActionOnly = (Request.Url.Query.IndexOf("taskactiononly") > -1) || (Request.UrlReferrer != null && Request.UrlReferrer.Query.IndexOf("taskactiononly") > -1);

        RegisterScript("table.js", "jquery.multipleselect.js", "notarialaction/select.js");

        _ActionKey = Action;

        if (String.IsNullOrEmpty(Request["nolayout"]))
        {
            LayoutPath = "~/views/layouts/popup.haml";
            TemplatePath = "~/views/notarialaction/select.haml";
        }
        else TemplatePath = "~/views/_table/table.haml";

        ProcessTable();
    }

    protected override IQueryable<NotarialAction> CustomFilter(NotarialServiceDataContext dc, IQueryable<NotarialAction> query)
    {
        //if (_TaskActionOnly)
            //return query.Where(na => na.IsAllowForTask);
        return query;
    }

    protected override void EntityLoaded(NotarialServiceDataContext dc, NotarialAction entity)
    {
        var company = entity;
        int pid = 0;
        if (entity.Id == 0 && !string.IsNullOrEmpty(Request["parentid"]) && Int32.TryParse(Request["parentid"], out pid))
        {
            entity.ParentId = pid;
            entity.Parent = dc.NotarialActions.Single(c => c.Id == pid);
        }

        if (!string.IsNullOrEmpty(Request["backtoparent"]))
            ViewData["backtoparent"] = true;

        if (entity.Id > 0)
            ViewData["parents"] = (from c in dc.NotarialActions where !c.Path.StartsWith(entity.Path) orderby c.FullName select c).ToList();

        ViewData["files"] = entity.NotarialActionFiles.Where(na => !na.IsDeleted).ToList();
    }

    protected override NameValueCollection FormatRow(object _entity)
    {
        var entity = (NotarialAction)_entity;
        var format = new NameValueCollection();
        foreach (var col in VisibleColumns)
        {
            if (ViewData.ContainsKey("excel"))
                format[col.Id] = col.ExcelFormat ?? "{@" + col.Id + "}";
            else
            {
                switch (col.Id.ToUpperInvariant())
                {
                    case "NAME":
                        //Добавить отступ в соответствии с уровнем вложенности
                        string img = entity.Level == 0 ? "<img src=\"img/smallarrowgrey.gif\" />" : String.Format("<img src=\"img/_.gif\" width=\"{0}\" height=\"1\" />", entity.Level * 20);
                        format[col.Id] = img + col.Format; ;
                        break;
                    default:
                        format[col.Id] = col.Format ?? "{@" + col.Id + "}";
                        break;
                }
            }
        }

        //Если первичного ключа нет среди колонок добавим формат для первичного ключа принудительно
        if (!string.IsNullOrEmpty(_PrimaryKey) && !VisibleColumns.Any(vc => vc.Id == _PrimaryKey))
            format[_PrimaryKey] = "{@" + _PrimaryKey + "}";

        //Зададим формат для колноки "RowClass"
        if (_HasRowClass) format["RowClass"] = "{@RowClass}";

        return format;
    }

    protected override void CreateFilterConditions(NotarialServiceDataContext dc)
    {
        Filter = new Filter<NotarialAction>();
        Filter.Conditions.Add(new BoolFilterCondition<NotarialAction>("IsArchive", "Архивный"));
    }

    [AllowedRole("DictionaryAdmin")]
    public override void View(string entityid)
    {
        base.View(entityid);
    }

    [AllowedRole("DictionaryAdmin")]
    public override void Create()
    {
        base.Create();
    }

    [AllowedRole("DictionaryAdmin")]
    public override void Delete()
    {
        base.Delete();
    }

    [AllowedRole("DictionaryAdmin")]
    public override void List()
    {
        base.List();
    }

    protected override void BeforeSubmit(NotarialServiceDataContext dc, NotarialAction entity)
    {     
        UploadFiles(entity, Session["User"] as User);
        base.BeforeSubmit(dc, entity);
    }

    /// <summary>
    /// Присоединить файлы к заявке
    /// </summary>
    private void UploadFiles(NotarialAction action, User user)
    {
        if (Request.Files.Count > 0)
        {
            for (int i = 0; i < Request.Files.Count; i++)
            {
                var file = Request.Files[i];
                var fileContent = RequestHelper.GetPostedFileContent(file);
                if (fileContent.Length == 0) continue;

                var tf = new NotarialActionFile();
                tf.Data = fileContent;
                tf.Created = DateTime.Now;
                tf.Name = System.IO.Path.GetFileName(file.FileName);
                action.NotarialActionFiles.Add(tf);
            }
        }
    }

    public void RemoveFile(string fileid)
    {
        var user = Session["user"] as User;
        using (var dc = new NotarialServiceDataContext())
        {
            int fid;
            Int32.TryParse(fileid, out fid);

            var file = dc.NotarialActionFiles.Single(f => f.Id == fid);

            try
            {
                file.IsDeleted = true;
                dc.SubmitChanges();
            }
            catch (Exception ex)
            {
                RenderJSON(new AJAXResult(ex));
                return;
            }
            RenderJSON(new AJAXResult { Id = fileid });
        }
    }

    public void ViewFile(string fileid)
    {
        using (var dc = new NotarialServiceDataContext())
        {
            int fid = 0;
            Int32.TryParse(fileid, out fid);

            var file = dc.NotarialActionFiles.Single(f => f.Id == fid);

            Response.ContentType = "application/octet-stream";
            Response.AppendHeader("Content-Disposition", "attachment;filename=\"" + file.Name + "\"");
            Response.HeaderEncoding = Encoding.GetEncoding("windows-1251");
            Response.ContentEncoding = Encoding.GetEncoding("windows-1251");
            byte[] bytes;
            try
            {
                bytes = Extractor.ExtractBytes(file.Data.ToArray());
            }
            catch
            {
                bytes = file.Data.ToArray();
            }
            Response.BinaryWrite(bytes);

            Response.Flush();
            Response.End();
        }
    }
}
